import { basicRoutes, asyncRoutes } from '@/router/index'
import { RouteRecordRaw } from 'vue-router'


interface State {
	routes: RouteRecordRaw[],
	permission_routes: RouteRecordRaw[]
}

interface Mutations<T = State> {
	MUTATIONS_GET_PERMISSIONS (
			state: T,
			permission_routes: RouteRecordRaw[]
	): void
}

interface ActionContext {
	commit<K extends keyof Mutations>(
			key: K,
			payload ?: Parameters<Mutations[K]>[1],
	): ReturnType<Mutations[K]>
}

interface Actions {
	ACTION_GENERATE_ROUTER ({ commit } : ActionContext , is_page_auth : any) : any
}

// 判断是否有权限
function hasPermission(roles: string[], route: any) {
	if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// 筛选路由
export function filterAsyncRoutes(routes: RouteRecordRaw[], roles: string[]) {
	const res: RouteRecordRaw[] = []
	routes.forEach(route=> {
		const r = { ...route }
		if (hasPermission(roles, r)) {
			if (r.children) {
				r.children = filterAsyncRoutes(r.children, roles)
			}
			res.push(r)
		}
	})
	return res
}

const state: State= {
	routes: [],
	permission_routes: [],
};

const mutations: Mutations = {
	MUTATIONS_GET_PERMISSIONS: (state: State, routes) => {
		state.routes = basicRoutes.concat(routes) 
		state.permission_routes = routes
		console.log(state.routes, '权限路由')
	}
};

const actions: Actions = {
	async ACTION_GENERATE_ROUTER ({ commit } ,roles: string[]) {
			let accessedRoutes: RouteRecordRaw[]
			if (roles.includes('admin')) {
				accessedRoutes = asyncRoutes
			} else {
				accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
			}
			commit('MUTATIONS_GET_PERMISSIONS',accessedRoutes)
	}
};

export default {
	namespaced: true,
	state,
	mutations,
	actions
};